import axios from 'axios'
import router from '../router'
import ElementUI from 'element-ui'
import nprogress from 'nprogress'

let http = axios.create({
    baseURL: '/api',
    withCredentials: true,
})

http.interceptors.request.use(function(config){
    nprogress.start()
    let rowPaths = ['/users/login','/users/getCaptcha','/users/verifyCaptcha']
    if(rowPaths.includes(config.url)){
        return config
    }else{
        let token = localStorage.getItem("crm-token") || ""
        config.headers['authorization'] = token
        return config
    }
    
})

http.interceptors.response.use(function(config){
    nprogress.done()
    //响应回的状态码是10022或1004的时候，需要跳转到登录页重新登录
    if(config.data.code==='10022' || config.data.code==='1004'){
        router.push('/login')
        localStorage.removeItem('crm-token')
        location.reload()
        //提示用户登录过期
        ElementUI.Message.error('登录过期，请重新登录')
        return
    }
    if(config.data.code==="10026"){
        ElementUI.Message.error('没有权限')
    }
    return config
})


export default http;